<?php


namespace App\Repository;


use App\Model\Group;
use Hyperf\Contract\LengthAwarePaginatorInterface;
use Hyperf\DbConnection\Db;

class GroupRepository
{
    public function index($request): LengthAwarePaginatorInterface
    {
        $self = $request->input('self', 0);

        return $self ?
            $this->my($request) :
            $this->all($request);
    }

    public function my($request): LengthAwarePaginatorInterface
    {
        $user_id = auth('api')->id();
        return Group::with('group_users')
            ->whereHas('group_users',
                fn($query) => $query->where('user_id', $user_id))
            ->when($request->has('keywords'),
                fn($query) => $query->where('name', 'LIKE', "%{$request->input('keywords')}%"))
            ->paginate($request->input('per_page', 15));
    }

    public function all($request): LengthAwarePaginatorInterface
    {
        return Group::query()
            ->when($request->has('keywords'),
                fn($query) => $query->where('name', 'LIKE', "%{$request->input('keywords')}%"))
            ->paginate($request->input('per_page', 15));
    }

    public function create($data)
    {
        Db::transaction(function () use ($data, &$group) {
            $group = Group::query()->create($data);
            (new GroupUserRepository())->create([
                'user_id' => $data['user_id'],
                'group_id' => $group->id,
                'type' => 1
            ]);
        });

        return $group;
    }
}